package com.hdsx.netty.tomcatserver.nio;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;

/**
 * @author 占贤银
 * time 2024/8/5 12:52
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 * todo 使用NIO实现一个简单版的Tomcat服务器
 */
public class XYTomcatServer {

    private Map<String, XYServlet> handlerMapping = new HashMap<>(10);

    private Properties prop = new Properties();

    private final int port;

    public XYTomcatServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        new XYTomcatServer(8888).start();
    }

    /**
     * 总结
     * 1、解析配置文件,封装成HandlerMapping url -> XYServlet 实现类
     * 2、浏览器就相当于客户端，接收客户端（浏览器发送过来的数据） 响应体中有一行 GET /firstServlet HTTP/1.1
     * 3、根据url获取到XYServlet对象，
     * 把接收到浏览器发送过来的数据封装成request对象，把写回给浏览器的数据封装成response对象
     */
    public void start(){
        // 1 todo 加载配置文件
        initServlet();
        // 2 todo 实现nio的真正处理业务逻辑
        initNioSocket();
    }

    private void initNioSocket() {
        try {
            Selector selector = Selector.open();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            // 设置非阻塞
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(port));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务已启动，监听端口:" + port);
            while (true) {
                // 不断的轮询
               selector.select();
               Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    handlerData(selector, selectionKey);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlerData(Selector selector, SelectionKey selectionKey) throws IOException {
        if (selectionKey.isAcceptable()) {
            ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
            SocketChannel socketChannel = channel.accept();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
        } else if (selectionKey.isReadable()) {
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int len = socketChannel.read(byteBuffer);
            if (len > 0) {
                byteBuffer.flip();
                String lines = new String(byteBuffer.array());
                String line = lines.split("\\n")[0];
                XYRequest request = new XYRequest(line);
                XYResponse response = new XYResponse(socketChannel);
                if (handlerMapping.containsKey(request.getUrl())) {
                    handlerMapping.get(request.getUrl()).service(request, response);
                } else {
                    response.write("Fond Not Page！");
                }
                socketChannel.close();
            } else {
                socketChannel.close();
            }
            byteBuffer.clear();

        }
    }

    public void initServlet() {
        InputStream in = null;
        try {
            in = this.getClass().getClassLoader()
                    .getResourceAsStream("web.properties");
            prop.load(in);
            for (Object k : prop.keySet()) {
                String key = k.toString();
                if (key.endsWith("url")) {
                    String url = prop.getProperty(key);
                    String servletName = key.replaceAll("url", "");
                    String className = prop.getProperty(servletName + "className");
                    Class aclazz = Class.forName(className);
                    if (aclazz.getSuperclass() == XYServlet.class) {
                        XYServlet servlet = (XYServlet) Class.forName(className).newInstance();
                        servlet.init();
                        handlerMapping.put(url, servlet);
                    }
                }
            }
            System.out.println("handlerMapping = " + handlerMapping);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
